<?php
/**
 * User:ayou chow
 * Date: 2019-11-05
 * Time: 15:53
 */

namespace app\admin\controller;


use app\common\GoogleAuthenticator;
use app\common\model\AdminModel;
use think\facade\Cookie;
use think\facade\Request;

class LoginController extends BaseController {
    public function initialize() {
    }

    public function index() {
        // 验证用户在线信息，包含google_secret加密值
        $is_login = $this->checkUser();
        if ($is_login && $this->getGoogleCodeCookie($this->userinfo->id, 1)) {
            $this->redirect(url('Index/index'));
        }

        $this->assign('config_pub', getConfigPub());
        return $this->fetch();
    }

    /**
     * google身份验证页面
     * 未登录过的显示二维码，登录过且用户表有生成google_code 则不显示二维码
     * @return mixed
     */
    public function gcode() {
        // 验证用户在线信息，包含google_secret加密值
        $is_login = $this->checkUser();
        if ($is_login && $this->getGoogleCodeCookie($this->userinfo->id, 1)) {
            $this->redirect(url('Index/index'));
        }

        if (!$is_login) {
            $this->redirect(url('login/index'));
        }

        // 判断secret 是否已经登录成功了
        $google_secret_cookie = $this->getGoogleCodeCookie($this->userinfo->id);

        // 获取google secret
        $google_secret = !empty($google_secret_cookie[2]) ? $google_secret_cookie[2] : $this->userinfo->google_secret;
        $data          = $this->googleAuthen($google_secret);

        if (!empty($data['secret'])) {
            $google_secret = $data['secret'];
            // 设置加密cookie
            $this->setGoogleCodeCookie($google_secret, $this->userinfo->id);
        }
        unset($data['secret']);

        // 二维码连接，如果登录用户已经设置过，则不显示二维码
        $google_code_url = !empty($data['qrcode_url']) ? $data['qrcode_url'] : '';
        if ($this->userinfo->google_secret) {
            $google_code_url = '';
        }
        $this->assign('google_code_url', $google_code_url);
        $this->assign('config_pub', getConfigPub());
        return $this->fetch();
    }

    /**
     * 用户登录 google 身份验证码验证正确
     * @return \think\response\Json|void
     */
    public function gcode_check() {
        $google_code = Request::post("googlecode");
        if (empty($google_code)) {
            return self::bulidFail("请输入google身份验证码");
        }

        $is_login = $this->checkUser();
        if (!$is_login) {
            return json(["code" => 2, "data" => [], 'msg' => '请先输入账户密码登录']);
        }

        $cookie_gsecret = $this->getGoogleCodeCookie($this->userinfo->id);
        if (!$cookie_gsecret) {
            return self::bulidFail("google身份验证码错误");
        }

        // 如果提交有google验证码，则验证是否正确
        $google_authen = new GoogleAuthenticator();
        $checkResult   = $google_authen->verifyCode($cookie_gsecret[2], $google_code, 1);

        if ($checkResult) {
            if (empty($this->userinfo->google_secret)) {
                AdminModel::where('id', $this->userinfo->id)->update(['google_secret' => $cookie_gsecret[2]]);
            }
            // 设置加密cookie 登录成功
            $this->setGoogleCodeCookie($cookie_gsecret[2] . '_1', $this->userinfo->id);
            return self::bulidSuccess("Google身份验证成功");
        }
        return self::bulidFail("Google身份验证失败");
    }

    public function editpwd() {
        return $this->fetch();
    }

    public function login() {
        $account = Request::param("account");
        $pwd     = openssl_encrypt($account . Request::param("password"), "DES-ECB", $this->OPENSSL_KEY);
        $vercode = Request::param("vercode");
        if (!captcha_check($vercode,'admin')) {
            return self::bulidFail("验证码有误");
        }

        $this->userinfo = AdminModel::where("account", $account)->where("password", $pwd)->find();
        $this->userinfo = AdminModel::where("account", $account)->find();
        if ($this->userinfo) {
            $this->userinfo->token = strtoupper(openssl_encrypt(date("YmdHis") . rand(10000, 99999), "DES-ECB", $this->OPENSSL_KEY));
            // $this->userinfo->token =  rand(10000, 99999);
            $this->userinfo->save();
            Cookie::set("uid", $this->userinfo->id);
            Cookie::set("token", $this->userinfo->token);
            Cookie::set("roleid", $this->userinfo->roleid);
            return self::bulidSuccess($this->userinfo, "登录成功");
        } else {
            return self::bulidFail("用户名或密码错误");
        }
    }


    public function editpwd_post() {
        $uid = Cookie::get("uid");
        if (!$uid) {
            $this->redirect("/admin/Login/redirectpage");
            exit();
        }
        $user   = AdminModel::where(['id' => $uid])->find();
        $oldpwd = openssl_encrypt($user->account . Request::param("oldpwd"), "DES-ECB", $this->OPENSSL_KEY);
        if ($oldpwd != $user->password) {
            return self::bulidFail('旧密码验证失败');
        }
        $user->password = openssl_encrypt($user->account . Request::param("newpwd"), "DES-ECB", $this->OPENSSL_KEY);
        if ($user->save()) {
            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function logout() {
        $this->delete_cookie();
        return self::bulidSuccess([], "登出成功");
    }

    public function redirectpage() {
        $this->delete_cookie();
        return $this->fetch();
    }

    /**
     * 删除后台登录缓存
     */
    private function delete_cookie() {
        Cookie::delete("uid");
        Cookie::delete("token");
        Cookie::delete("googlesecret");
    }

    /**
     * google身份验证获取url
     * @param string $secret 生成的秘钥
     * @return array
     */
    private function googleAuthen($secret = '') {
        // 加载google身份验证器
        $google_authen = new GoogleAuthenticator();
        if (empty($secret)) {
            $secret = $google_authen->createSecret();
        }

        // 获取二维码url
        $qrcode_url = $google_authen->getQRCodeGoogleUrl('login', $secret);
        $data       = array(
            'qrcode_url' => $qrcode_url,
            'secret'     => $secret,
        );
        return $data;
    }
}